﻿using AuSys.Utils.Reflection;
using FluentValidation;
using FluentValidation.Resources;
using System.ComponentModel;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;

namespace AuSys.Services.App.Validation
{
    public static class FluentValidationSetup
    {
        public static IServiceCollection SetupFluentValidation(this IServiceCollection services)
        {
            var validators = TypeSearcher.Search<IValidator>();
            validators.ForEach(t =>
            {
                services.AddScoped(t);
            });

            ValidatorOptions.Global.DefaultRuleLevelCascadeMode = CascadeMode.Stop;
            ValidatorOptions.Global.DisplayNameResolver
                = (Type type, MemberInfo? member, LambdaExpression? exp) =>
                {
                    member ??= exp?.ReturnType ?? type;
                    var attr = member.GetCustomAttribute<DisplayNameAttribute>();
                    if (attr is { })
                        return attr.DisplayName;
                    return member.Name;
                };
            ValidatorOptions.Global.LanguageManager = new CustomLanguageManager()
            {
                Culture = new CultureInfo(CustomLanguageManager.zhHans)
            };

            return services;
        }

        private class CustomLanguageManager : LanguageManager
        {
            public const string zhHans = "zh-Hans";
            public CustomLanguageManager()
            {
                AddTranslation(zhHans, "NotEmptyValidator", "<{PropertyName}>不能为空");
                AddTranslation(zhHans, "NotNullValidator", "<{PropertyName}>不能为空");
                AddTranslation(zhHans, "MaximumLengthValidator", "<{PropertyName}>不能超过{MaxLength}字符");
                AddTranslation(zhHans, "MinimumLengthValidator", "<{PropertyName}>不能少于{MinLength}字符");
            }
        }
    }
}
